<?
/*
		topGames: an iRC games bot
		Copyright (C) 2008 Marcos Garc�a <marcosgdf@gmail.com>
    
		This file is part of topGames

		This program is free software: you can redistribute it and/or modify
		it under the terms of the GNU General Public License as published by
		the Free Software Foundation, either version 3 of the License, or
		any later version.

		This program is distributed in the hope that it will be useful,
		but WITHOUT ANY WARRANTY; without even the implied warranty of
		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
		GNU General Public License for more details.

		You should have received a copy of the GNU General Public License
		along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

class topgames {
	var $dbconnected;
	var $dbsock;
	var $ircconnected;
	var $irctries = 0;
	var $sockfd;
	var $logfd;
	var $ping = 0;
	var $ctime;
	var $portero;
	var $mdbRetry;

	// mysql functions
	
	/**
	 * Connects to a mySQL server
	 * @return unknown_type
	 */
	function dbConnect() {
		if (DB_METHOD == 'socket') $host = ':'.DB_SOCK;
		elseif (DB_METHOD == 'ip') $host = DB_HOST.':'.DB_PORT;
		$this->dbsock = @mysql_pconnect($host,DB_USER,DB_PASS);
		if (!$this->dbsock) {
            global $_CFG;
			$this->dbconnected = false;
			$message = "Error al conectar al servidor mysql";
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($message);
			die('[-] '.$message."\n");
		}
		else {
			$this->dbconnected = true;
			return $this->dbsock;
		}
	}
	/**
	 * Returns wether the bot is connected to the database or not
	 * @return unknown_type
	 */
	function isDbConnected() {
		return $this->dbconnected;
	}
	/**
	 * Selects the database in the mysql Server
	 * @return unknown_type
	 */
	function dbSelect() {
		mysql_select_db(DB_NAME);
	}
	/**
	 * Sends a query to the mysql Server
	 * @param $query
	 * @return unknown_type
	 */
	function dbSend($query) {
		$q = mysql_query($query) or die($this->dbError());
		return $q;
	}
	/**
	 * It does this function when an error is detected in the database
	 * @return unknown_type
	 */
	function dbError() {
		global $_CFG;
		if (LOG_STATUS && (in_array('errors',$_CFG["LOG_REC"]))) $this->writeLog('Error de mysql: '.mysql_error());
		die('[-] Error de mysql: '.mysql_error()."\n");
	}
 
	// irc functions
	
	/**
	 * Connects to the iRC Server
	 * @return unknown_type
	 */
	function ircConnect() {
		global $_CFG;
		$ip = gethostbyname(IRC_SERVER);
		$sockfd = @fsockopen($ip,IRC_PORT,$errno,$errstr,20);
		if (!$sockfd) {
			if (!IRC_TRIES) $tries = IRC_TRIES;
			else $tries = 3;
			if ($this->irctries < $tries) {
				$this->irctries = ++$this->irctries;
				if (LOG_STATUS && (in_array('status',$_CFG["LOG_REC"]))) $this->writeLog("Intento ".$this->irctries." de $tries -> reconectando");
				echo "[-] Intento ".$this->irctries." de $tries -> reconectando\n";
				$this->ircConnect();
			}
			elseif ($this->irctries > $tries) {
				if (LOG_STATUS && (in_array('errors',$_CFG["LOG_REC"]))) $this->writeLog("Error al conectar al servidor irc: $errno - $errstr");
				die("[-] Error al conectar al servidor irc: $errno - $errstr\n");
			}
		}
		else {
			echo '[+] conectado'."\n";
			$this->sockfd = $sockfd;
			stream_set_timeout($this->sockfd,0); 
			return $this->sockfd;
		}
	}
	/**
	 * Says wether the bot is connected to the iRC Network or not
	 * @return unknown_type
	 */
	function isIrcConnected() {
		return $this->ircconnected;
	}
	/**
	 * Returns the socket identificator
	 * @return unknown_type
	 */
	function getIrcSocket() {
		return $this->sockfd;
	}
	/**
	 * Identifies the bot in the iRC Network
	 * @return unknown_type
	 */
	function ircIdentify() {
		$this->ircSend("USER ".IRC_NICK." - - :- \n");
		$password = IRC_PASS;
		if (!empty($password)) $this->ircSend("NICK ".IRC_NICK."!".IRC_PASS." - \r\n");
		else $this->ircSend("NICK ".IRC_NICK." - \r\n");
	}
	/**
	 * Changes the content of the 'ircconnected' variable. It could be true or false and it is supposed to say if the bot is connected or not to the iRC Network
	 * @param $status
	 * @return unknown_type
	 */
	function changeIrcStatus($status) {
		$this->ircconnected = $status;
	}
	/**
	 * Sends something to the iRC connection
	 * @param $data
	 * @return unknown_type
	 */
	function ircSend($data) {
		fputs($this->sockfd,$data);
	}
	/**
	 * Joins a channel and updates it's status in the Database
	 * @param $channel
	 * @return unknown_type
	 */
	function joinChannel($channel) {
		$this->ircSend("JOIN :$channel\r\n");
		$this->dbSend("UPDATE ".DB_PREFIX."autojoin SET `is_in`='1' WHERE `channel`='$channel' AND `bot_number`='".BOT_NUMBER."'");
	}
	/**
	 * Parts a channel with(out) a message and then it updates it's status in the database
	 * @param $channel
	 * @param $message
	 * @return unknown_type
	 */
	function partChannel($channel,$message=NULL) {
		$this->ircSend("PART $channel :$message\r\n");
		$this->dbSend("UPDATE ".DB_PREFIX."autojoin SET is_in='0' WHERE `channel`='$channel' AND `bot_number`='".BOT_NUMBER."'");
		$this->dbSend("DELETE FROM ".DB_PREFIX."channelusers WHERE `channel`='$channel' AND `bot_number`='".BOT_NUMBER."'");
	}
	/**
	 * Sends a message to an user or a channel
	 * @param $target
	 * @param $data
	 * @param $includeLogo
	 * @return unknown_type
	 */
	function ircMsg($target,$data,$includeLogo=NULL) {
		if ($includeLogo) $data = LOGO.' '.$data;
		$data = mb_convert_encoding($data, ENCODING, 'UTF-8');
		$this->ircSend("PRIVMSG $target :$data\r\n");
	}
	/**
	 * Sends something to the iRC Server in the appropiate format
	 * @param $data
	 * @return unknown_type
	 */
	function ircRaw($data) {
		$this->ircSend("$data\r\n");
	}
	/**
	 * This is an initial check. It checks if there're all the neccesary files in the folder and 'bcmath' and 'curl' extension are installed. It also checks if the configuraton has been done properly
	 * @return unknown_type
	 */
	function doCheck() {
		global $_CFG;
		if (!is_dir(MASTER_DIR.'logs')) {
			if (!mkdir(MASTER_DIR.'logs')) die('[-] No existe el directorio logs. [-] No se pudo crear el directorio logs'."\n");
		} elseif (!is_dir(MASTER_DIR.'logs/channels')) {
			if (!mkdir(MASTER_DIR.'logs/channels')) die('[-] No existe el directorio logs/channels. No se pudo crear el directorio channels'."\n");
		} elseif (!file_exists(MASTER_DIR.'config.php')) die('[-] No existe el archivo config.php'."\n");
		elseif (!file_exists(MASTER_DIR.'class/class.const.php')) die('[-] No existe el archivo class/class.const.php'."\n");
		elseif (!file_exists(MASTER_DIR.'class/class.events.php')) die('[-] No existe el archivo class/class.events.php'."\n");
		elseif (!file_exists(MASTER_DIR.'class/class.juegos.php')) die('[-] No existe el archivo class/class.juegos.php'."\n");
		elseif (!file_exists(MASTER_DIR.'class/class.misc.php')) die('[-] No existe el archivo class/class.misc.php'."\n");
		elseif (!file_exists(MASTER_DIR.'class/class.raw.php')) die('[-] No existe el archivo class/class.raw.php'."\n");
		elseif (!file_exists(MASTER_DIR.'class/class.sockets.php')) die('[-] No existe el archivo class/class.sockets.php'."\n");
		elseif (!IRC_SERVER || (!is_string(IRC_SERVER))) {
			$msg = 'Error en config.php: IRC_SERVER esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!IRC_PORT || (!is_numeric(BOT_NUMBER))) {
			$msg = 'Error en config.php: IRC_PORT esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!IRC_NICK || (!is_string(IRC_NICK))) {
			$msg = 'Error en config.php: IRC_NICK esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (defined(IRC_PASS) && (!IRC_PASS)) {
			$msg = 'Error en config.php: IRC_PASS esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!P_CHANNEL || (!is_string(P_CHANNEL))) {
			$msg = 'Error en config.php: BOT_NUMBER esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!CHANNEL || (!is_string(CHANNEL))) {
			$msg = 'Error en config.php: BOT_NUMBER esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!BOT_NUMBER || (!is_numeric(BOT_NUMBER))) {
			$msg = 'Error en config.php: BOT_NUMBER esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!DB_HOST || (!is_string(DB_HOST))) {
			$msg = 'Error en config.php: DB_HOST esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!DB_USER || (!is_string(DB_USER))) {
			$msg = 'Error en config.php: DB_USER esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!DB_NAME || (!is_string(DB_NAME))) {
			$msg = 'Error en config.php: DB_NAME esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!DB_PORT || (!is_numeric(DB_PORT))) {
			$msg = 'Error en config.php: DB_PORT esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!MINIDB_SERVER || (!is_string(MINIDB_SERVER))) {
			$msg = 'Error en config.php: MINIDB_SERVER esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!MINIDB_PORT || (!is_numeric(MINIDB_PORT))) {
			$msg = 'Error en config.php: MINIDB_PORT esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!MINIDB_USER || (!is_string(MINIDB_USER))) {
			$msg = 'Error en config.php: MINIDB_USER esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!MINIDB_PASS) {
			$msg = 'Error en config.php: MINIDB_PASS esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!LOG_STATUS || (!is_bool(LOG_STATUS))) {
			$msg = 'Error en config.php: LOG_STATUS esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (LOG_STATUS == true) {
			if (!LOG_WILDCARD || (!is_string(LOG_WILDCARD))) {
				$msg = 'Error en config.php: LOG_WILDCARD esta vacio o es incorrecto';
				if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
				die("[-] $msg\n");
			}
			else {
				global $_CFG;
				if (empty($_CFG["LOG_REC"]) || (!is_array($_CFG["LOG_REC"]))) {
					$msg = 'Error en config.php: $_CFG["LOG_REC"] esta vacio o es incorrecto';
		          	if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
        			die("[-] $msg\n");
				}
				else {
					$count = count($_CFG["LOG_REC"]);
					if (!$count) {
						$msg = 'Error en config.php: $_CFG["LOG_REC"] tiene que tener al menos 1 opcion activada';
						if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
						die("[-] $msg\n");
					}
				}
			}
		}
		if (!WEB_INFOBANKS) {
			$msg = 'Error en config.php: WEB_INFOBANKS esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!is_bool(PING_SERVER)) {
			$msg = 'Error en config.php: PING_SERVER esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (PING_SERVER == true) {
			if (!BOT_TOKEN || (!is_string(BOT_TOKEN) || (strlen(BOT_TOKEN) < 30))) {
				$msg = 'Error en config.php: BOT_TOKEN esta vacio o es incorrecto';
				if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
				die("[-] $msg\n");
			} elseif (!PING_PORT || (!is_numeric(PING_PORT))) {
				$msg = 'Error en config.php: PING_PORT esta vacio o es incorrecto';
				if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
				die("[-] $msg\n");
			} elseif (!PING_PATH || (!is_string(PING_PATH))) {
				$msg = 'Error en config.php: PING_PATH esta vacio o es incorrecto';
				if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
				die("[-] $msg\n");
			} elseif (!PING_FREQUENCY || (!is_numeric(PING_PORT))) {
				$msg = 'Error en config.php: PING_FREQUENCY esta vacio o es incorrecto';
				if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
				die("[-] $msg\n");
			}
		} elseif (!ENCODING) {
			$msg = 'Error en config.php: ENCODING esta vacio o es incorrecto';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		}
		if (!function_exists('bcadd') || (!function_exists('bccomp') || (!function_exists('bcdiv') || (!function_exists('bcsub') || (!function_exists('bcmul')))))) {
			$msg = 'Para poder ejecutar el bot, es necesaria la extension \'bcmath\' de php';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		} elseif (!function_exists('curl_init')) {
			$msg = 'Para poder ejecutar el bot, es necesaria la extension \'curl\' de php';
			if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($msg);
			die("[-] $msg\n");
		}
	}

	// other functions

	// ignore functions

	/**
	 * Checks wether a nick is ignored or not
	 * @param $nick
	 * @return unknown_type
	 */
	function isIgnored($nick) {
		if ($this->isNickRegistered($nick)) {
			$query = $this->dbSend("SELECT is_ignored FROM ".DB_PREFIX."users WHERE `nick`='$nick'");
			$result = mysql_result($query,0);
			if (!$result) {
				$query = $this->dbSend("SELECT COUNT(id) FROM ".DB_PREFIX."ignores WHERE `nick`='$nick'");
				$result = mysql_result($query,0);
				if ($result >= 1) {
					$query = $this->dbSend("SELECT `ctime`,`time` FROM ".DB_PREFIX."ignores WHERE `nick`='$nick'");
					$result = mysql_fetch_array($query,MYSQL_NUM);
					$ctime = time() - $result[0];
					if ($ctime >= $result[1]) {
						$this->dbSend("DELETE FROM ".DB_PREFIX."ignores WHERE `nick`='$nick'");
						$return = false;
					}
					else $return = true;
				}
				else $return = false;
			}
			else $return = true;
			return $return;
		}
	}
	/**
	 * Adds an ignore to the specified user with the specified time
	 * @param $nick
	 * @param $time
	 * @return unknown_type
	 */
	function addIgnore($nick,$time) {
		$this->dbSend("INSERT INTO ".DB_PREFIX."ignores SET `nick`='$nick', `ctime`='".time()."', `time`='$time'");
	}
	/**
	 * Adds an ignore to an user with the default ignore time
	 * @param $nick
	 * @return unknown_type
	 */
	function addDefaultIgnore($nick) {
		$query = $this->dbSend("SELECT valor FROM ".DB_PREFIX."settings WHERE `campo`='ignore_secs'");
		$this->addIgnore($nick,mysql_result($query,0));
	}

	// lines functions

	/**
	 * Gets the lines written by an user
	 * @param $nick
	 * @return unknown_type
	 */
	function getLines($nick) {
		$query = $this->dbSend("SELECT lineas FROM ".DB_PREFIX."users WHERE `nick`='$nick'");
		$result = mysql_result($query,0);
		return $result;
	}
	/**
	 * Calculates the level of the user
	 * @param $nick
	 * @return unknown_type
	 */
	function getLevel($nick,$lines=NULL) {
		if (!$lines) $lines = $this->getLines($nick);
		$level = 1;
		while ($level >= 0) {
			$linesLevel = $this->getLevelLines($level);
			if ($lines > $linesLevel) $level++;
			elseif ($lines < $linesLevel) break;
		}
		return $level;
	}
	/**
	 * Calculates the neccesary lines to be on some level
	 * @param $level
	 * @return unknown_type
	 */
	function getLevelLines($level) {
		$calc = (100 + (350 * $level));
		if ($level >= 10) $calc = (100 + (700 * $level));
		if ($level >= 15) $calc = (100 + (900 * $level));
		return $calc;
	}
	/**
	 * Adds a line to some user
	 * @param $nick
	 * @return unknown_type
	 */
	function addLine($nick) {
		$lineas = $this->getLines($nick);
		$calc = ++$lineas;
		$this->dbSend("UPDATE ".DB_PREFIX."users SET `lineas`='$calc' WHERE `nick`='$nick'");
	}
	/**
	 * Checks if the user has uploaded to a higher level or not
	 * @param $nick
	 * @param $canal
	 * @return unknown_type
	 */
	function checkLines($nick,$canal) {
		$lines = $this->getLines($nick);
		$level = $this->getLevel($nick);
		$postLevel = ++$level;
		if ($lines > $this->getLevelLines($postLevel)) {
			$postPostLevel = ++$postLevel;
			$remainingLines = $this->getLevelLines($postPostLevel) - $lines;
			$this->ircMsg($nick,"Enhorabuena ".$this->h($nick).", acabas de subir al nivel".$this->h(" $postLevel").", como recompensa, recibes".$this->h(" 1")." topBono");
			$this->addBonos($nick,1);
			$this->ircMsg(CHANNEL,"El usuario ".$this->h($nick)." ha subido al nivel".$this->h(" $postLevel")." con".$this->h(" $lines")." lineas", true);
		}
	}

	// nick functions

	/**
	 * Checks wether a nick is on the database or not
	 * @param $nick
	 * @return unknown_type
	 */
	function isNickRegistered($nick) {
		$query = $this->dbSend("SELECT COUNT(id) FROM ".DB_PREFIX."users WHERE `nick`='$nick'");
		$result = mysql_result($query,0);
		if (!$result) return false; else return true;
	}
	/**
	 * Checks wether a nick is suspended or not
	 * @param $nick
	 * @return unknown_type
	 */
	function isNickSuspended($nick) {
		$query = $this->dbSend("SELECT is_active FROM ".DB_PREFIX."users WHERE `nick`='$nick'");
		$result = mysql_result($query,0);
		if (!$result) return true; else return false;
	}
	/**
	 * Checks wether a nick can signup on the database or not
	 * @param $nick
	 * @return unknown_type
	 */
	function isNickForbidden($nick) {
		$query = $this->dbSend("SELECT COUNT(id) FROM ".DB_PREFIX."forbid WHERE `type`='n' AND `data`='$nick'");
		$result = mysql_result($query,0);
		if (!$result) return false; else return true;
	}
	/**
	 * Checks wether a nick is an operator or not
	 * @param $nick
	 * @return unknown_type
	 */
	function isNickOper($nick) {
		$query = $this->dbSend("SELECT `gid` FROM ".DB_PREFIX."users WHERE `nick`='$nick'");
		$result = mysql_result($query,0);
		if ($result > 0) return $result; else return false;
	}
	/**
	 * Creates a new user
	 * @param $nick
	 * @param $created_by
	 * @return unknown_type
	 */
	function newUser($nick,$created_by) {
		$this->dbSend("INSERT INTO ".DB_PREFIX."users SET `nick`='$nick', `created_by`='$created_by', `ctime`='".time()."', `lineas`='0'");
		$this->mdbSend("CREATE $nick");
		$this->addMoney($nick,1000);
		$this->addBonos($nick,1);
	}
	/**
	 * Gets the status of the nick
	 * @param $nick
	 * @param $verbose
	 * @return unknown_type
	 */
	function getNickStatus($nick,$verbose=0) {
		$query = $this->dbSend("SELECT `gid` FROM ".DB_PREFIX."users WHERE `nick`='$nick'");
		if (mysql_num_rows($query)) {
			$result = mysql_result($query,0);
			if ($verbose == true) {
				$status0 = array('1','2','3','4','5');
				$status1 = array('user','pre-oper','oper','co-admin','admin');
				$status = str_replace($status0, $status1, $result);
				return $status;
			}
			else return $result;
		}
		else return 0;
	}
	
	//floodcheck functions
	
	/**
	 * Adds a flood flag to an user
	 * @param $nick
	 * @return unknown_type
	 */
	function addFlood($nick) {
		$this->dbSend("INSERT INTO ".DB_PREFIX."floodcheck SET `nick`='$nick', `ctime`='".time()."'");
	}
	/**
	 * Checks wether a nick can interact with the bot or not (because of flood protection)
	 * @param $nick
	 * @return unknown_type
	 */
	function getFlood($nick) {
		$query = $this->dbSend("SELECT COUNT(nick) FROM ".DB_PREFIX."floodcheck WHERE `nick`='$nick'");
		$result = mysql_result($query,0);
		return $result;
	}
	/**
	 * Checks wether a nick has already an ignore. If there are 3 ignores, then he's ignored for 60 seconds
	 * @param $nick
	 * @return unknown_type
	 */
	function checkFlood($nick) {
		$this->addFlood($nick);
		$query = $this->dbSend("SELECT id,ctime FROM ".DB_PREFIX."floodcheck WHERE `nick`='$nick'");
		if (mysql_num_rows($query) >= 1) {
			$erased = 0;
			while ($row = mysql_fetch_row($query)) {
				$resta = time() - $row[1];
				if ($resta >= 3) {
					$this->dbSend("DELETE FROM ".DB_PREFIX."floodcheck WHERE `id`='".$row[0]."'");
					++$erased;
				}
			}
			if ($erased > 0) $total = mysql_num_rows($query) - $erased;
			else $total = mysql_num_rows($query);
			if ($total == 3) {
				$this->addIgnore($nick,60);
				$this->ircMsg(CHANNEL,"Añadido un ignore de 60 segundos a ".$this->h($nick)." por flood", true);
			}
		}
	}
 
	// channel functions
 	
	/**
	 * Checks if a channel is on the autojoin or not
	 * @param $channel
	 * @return unknown_type
	 */
	function isChannelAutojoin($channel) {
		$query = $this->dbSend("SELECT COUNT(id) FROM ".DB_PREFIX."autojoin WHERE `channel`='$channel' AND `is_active`='1' AND `bot_number`='".BOT_NUMBER."'");
		$result = mysql_result($query,0);
		if (!$result) return false; else return true;
	}
	/**
	 * Checks if a channel could be registered or not
	 * @param $channel
	 * @return unknown_type
	 */
	function isChannelForbidden($channel) {
		$query = $this->dbSend("SELECT COUNT(id) FROM ".DB_PREFIX."forbid WHERE `type`='c' AND `data`='$channel'");
		$result = mysql_result($query,0);
		if (!$result) return false; else return true;
	}
	/**
	 * Checks if the bot is in a channel or not
	 * @param $channel
	 * @return unknown_type
	 */
	function isChannelIn($channel) {
		$query = $this->dbSend("SELECT is_in FROM ".DB_PREFIX."autojoin WHERE `channel`='$channel' AND `bot_number`='".BOT_NUMBER."'");
		if (mysql_num_rows($query)) $result = mysql_result($query,0);
		if (!$result) return false; else return true;
	}
	/**
	 * Checks if a channel is on the database or not
	 * @param $channel
	 * @return unknown_type
	 */
	function isChannelRegistered($channel) {
		$query = $this->dbSend("SELECT COUNT(id) FROM ".DB_PREFIX."autojoin WHERE `channel`='$channel'");
		$result = mysql_result($query,0);
		if (!$result) return false; else return true;
	}
	/**
	 * Checks wether a channel is suspended or not
	 * @param $channel
	 * @return unknown_type
	 */
	function isChannelSuspended($channel) {
		$query = $this->dbSend("SELECT COUNT(id) FROM ".DB_PREFIX."autojoin WHERE `channel`='$channel' AND `is_active`='0'");
		$result = mysql_result($query,0);
		if (!$result) return false; else return true;
	}
	/**
	 * Gets the list of channels that the bot has to be in
	 * @return unknown_type
	 */
	function getAutojoin() {
		$query = $this->dbSend("SELECT channel FROM ".DB_PREFIX."autojoin WHERE `is_active`='1' AND `bot_number`='".BOT_NUMBER."'");
		$result = array();
		while ($row=mysql_fetch_row($query)) $result[] = $row[0];
		return $result;
	}
	/**
	 * Gets a list of channels were the bot is in or not.
	 * @param $in
	 * @return unknown_type
	 */
	function getChannels($in) {
		$query = $this->dbSend("SELECT channel FROM ".DB_PREFIX."autojoin WHERE `is_active`='1' AND is_in='$in' AND `bot_number`='".BOT_NUMBER."'");
		$result = array();
		while ($row=mysql_fetch_row($query)) $result[] = $row[0];
		return $result;
	}
	/**
	 * Gets a list of suspended channels
	 * @return unknown_type
	 */
	function getSuspendedChannels() {
		$query = $this->dbSend("SELECT channel FROM ".DB_PREFIX."autojoin WHERE `is_active`='0' AND `bot_number`='".BOT_NUMBER."'");
		$result = array();
		while ($row=mysql_fetch_row($query)) $result[] = $row[0];
		return $result;
	}
	/**
	 * Gets a list of channels in the database
	 * @return unknown_type
	 */
	function getRegisteredChannels() {
		$query = $this->dbSend("SELECT channel FROM ".DB_PREFIX."autojoin WHERE `bot_number`='".BOT_NUMBER."'");
		$result = array();
		while ($row=mysql_fetch_row($query)) $result[] = $row[0];
		return $result;
	}
	/**
	 * Returns the number of users of a channel
	 * @param $channel
	 * @return unknown_type
	 */
	function getCountUsersChannel($channel) {
		$query = $this->dbSend("SELECT COUNT(id) FROM ".DB_PREFIX."channelusers WHERE `channel`='$channel' AND `bot_number`='".BOT_NUMBER."'");
		$result = mysql_result($query,0);
		return $result;
	}
	/**
	 * Deletes a channel from the database
	 * @param $channel
	 * @return unknown_type
	 */
	function delChannel($channel) {
		$this->dbSend("DELETE FROM ".DB_PREFIX."autojoin WHERE `channel`='$channel' AND `bot_number`='".BOT_NUMBER."'");
	}
	/**
	 * Adds a channel into the database
	 * @param $channel
	 * @param $data
	 * @return unknown_type
	 */
	function addChannel($channel,$data) {
		$this->dbSend("INSERT INTO ".DB_PREFIX."autojoin SET `channel`='$channel', `bot_number`='".BOT_NUMBER."', `added_by`='$data', `ctime`='".time()."'");
	}

	//bote functions
 
	/**
	 * Adds money to the bote
	 * @param $quantity
	 * @return unknown_type
	 */
	function addMoneyBote($quantity) {
		$bonos = $this->getBonosBote();
		$money = $this->getMoneyBote();
		$postMoney = $money + $quantity;
		$this->dbSend("INSERT INTO ".DB_PREFIX."bote SET `bonos`='$bonos', `dinero`='$postMoney', ctime='".time()."'");
	}
	/**
	 * Adds bonos to the bote
	 * @param $quantity
	 * @return unknown_type
	 */
	function addBonosBote($quantity) {
		$bonos = $this->getBonosBote();
		$money = $this->getMoneyBote();
		$postBonos = $bonos + $quantity;
		$this->dbSend("INSERT INTO ".DB_PREFIX."bote SET `bonos`='$postBonos', `dinero`='$money', ctime='".time()."'");
	}
	/**
	 * Deletes money from the bote
	 * @param $quantity
	 * @return unknown_type
	 */
	function delMoneyBote($quantity) {
		$bonos = $this->getBonosBote();
		$money = $this->getMoneyBote();
		$postMoney = $money - $quantity;
		$this->dbSend("INSERT INTO ".DB_PREFIX."bote SET `bonos`='$bonos', `dinero`='$postMoney', ctime='".time()."'");
	}
	/**
	 * Deletes bonos from the bote
	 * @param $quantity
	 * @return unknown_type
	 */
	function delBonosBote($quantity) {
		$bonos = $this->getBonosBote();
		$money = $this->getMoneyBote();
		$postBonos = $bonos - $quantity;
		$this->dbSend("INSERT INTO ".DB_PREFIX."bote SET `bonos`='$postBonos', `dinero`='$money', ctime='".time()."'");
	}
	/**
	 * Erases the bote
	 * @return unknown_type
	 */
	function eraseBote() {
		$this->dbSend("INSERT INTO ".DB_PREFIX."bote SET `bonos`='0', `dinero`='0', `ctime`='".time()."'");
	}
	/**
	 * Erases just the money of the bote
	 * @return unknown_type
	 */
	function eraseMoneyBote() {
		$bonos = $this->getBonosBote();
		$this->dbSend("INSERT INTO ".DB_PREFIX."bote SET `bonos`='$bonos', `dinero`='0'");
	}
	/**
	 * Erases just the bonos of the bote
	 * @return unknown_type
	 */
	function eraseBonosBote() {
		$dinero = $this->getMoneyBote();
		$this->dbSend("INSERT INTO ".DB_PREFIX."bote SET `bonos`='0', `dinero`='$dinero'");
	}
	/**
	 * Gets the amount of money that the bote has
	 * @return unknown_type
	 */
	function getMoneyBote() {
		$query = $this->dbSend("SELECT dinero FROM ".DB_PREFIX."bote ORDER BY id DESC LIMIT 0,1");
		if (mysql_num_rows($query)) {
			$result = mysql_result($query,0);
			return $result;
		}
		else return false;
	}
	/**
	 * Gets the amount of bonos that the bote has
	 * @return unknown_type
	 */
	function getBonosBote() {
		$query = $this->dbSend("SELECT bonos FROM ".DB_PREFIX."bote ORDER BY id DESC LIMIT 0,1");
		if (mysql_num_rows($query)) {
			$result = mysql_result($query,0);
			return $result;
		}
		else return false;
	}
	/**
	 * Maintains the log of the bote
	 * @return unknown_type
	 */
	function checkBote() {
		$query = $this->dbSend("SELECT id FROM ".DB_PREFIX."bote ORDER BY id DESC");
		$result = mysql_num_rows($query);
		if ($result > 50) {
			$query = $this->dbSend("SELECT id FROM ".DB_PREFIX."bote ORDER BY id DESC LIMIT 50,$result");
			$result = mysql_fetch_array($query,MYSQL_NUM);
			foreach ($result AS $id) $this->dbSend("DELETE FROM ".DB_PREFIX."bote WHERE id='$id'");
		}
	}
 
	// topgames miniDB functions
 
	/**
	 * Sends a query to the miniDB server
	 * @param $query
	 * @return unknown_type
	 */
	function mdbSend($query) {
		$query = rawurlencode($query);
		$url = MINIDB_SERVER.':'.MINIDB_PORT.'/'.MINIDB_PATH.'?q='.$query;
		$curl = curl_init($url);
		curl_setopt($curl,CURLOPT_USERAGENT,"topgames ".TOPGAMES_VERSION);
		curl_setopt($curl,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
		curl_setopt($curl,CURLOPT_USERPWD, MINIDB_USER.':'.MINIDB_PASS);
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
		$result = curl_exec($curl);
		curl_close($curl);
		if (substr($result, 0, 5) == "Error" || (strlen($result) == 0)) {
            global $_CFG;
			if (!$this->mdbRetry) {
				$textMessage = 'Error al obtener los datos del miniDB server. Reintentando... ';
				if (strlen($result) == 0) $textMessage .= '(Sin respuesta)'; else $textMessage .= '('.$result.')';
				$this->ircMsg(CHANNEL, $textMessage, true);
				if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($textMessage);
				$this->mdbRetry = true;
				$this->mdbSend($query);
			}
			else {
				$message = "Reintento fallido. Cerrando el bot...";
				$this->ircMsg(CHANNEL, $message, true);
				if (LOG_STATUS && (in_array('errors', $_CFG['LOG_REC']))) $this->writeLog($message." $result");
				die("[-] $message $result\n");
			}
			return false;
		}
		else return $result;
	}
 
	// money functions
 
	/**
	 * Adds money to an user
	 * @param $nick
	 * @param $quantity
	 * @return unknown_type
	 */
	function addMoney($nick,$quantity) {
		$pastMoney = $this->getMoney($nick);
		$postMoney = bcadd($pastMoney,$quantity);
		$this->mdbSend("UPDATE DINERO $nick $postMoney");
	}
	/**
	 * Deletes money from an user
	 * @param $nick
	 * @param $quantity
	 * @return unknown_type
	 */
	function delMoney($nick,$quantity) {
		$pastMoney = $this->getMoney($nick);
		$postMoney = bcsub($pastMoney,$quantity);
		if ((string) bccomp($postMoney,0) == '-1') $postMoney = 0;
		$this->mdbSend("UPDATE DINERO $nick $postMoney");
	}
	/**
	 * Gets the amount of money that an user has
	 * @param $nick
	 * @return unknown_type
	 */
	function getMoney($nick) {
		$query = $this->mdbSend("SELECT DINERO $nick");
		return $query;
	}
	/**
	 * Sets the amount of money that an user should have
	 * @param $nick
	 * @param $quantity
	 * @return unknown_type
	 */
	function setMoney($nick,$quantity) {
		$this->mdbSend("UPDATE DINERO $nick $quantity");
	}
 
	//bonos functions 
 
	/**
	 * Adds bonos to an user
	 * @param $nick
	 * @param $quantity
	 * @return unknown_type
	 */
	function addBonos($nick,$quantity) {
		$pastBonos = $this->getBonos($nick);
		$postBonos = bcadd($pastBonos,$quantity);
		$this->mdbSend("UPDATE BONOS $nick $postBonos");
	}
	/**
	 * Deletes bonos from an user
	 * @param $nick
	 * @param $quantity
	 * @return unknown_type
	 */
	function delBonos($nick,$quantity) {
		$pastBonos = $this->getBonos($nick);
		$postBonos = bcsub($pastBonos,$quantity);
		$this->mdbSend("UPDATE BONOS $nick $postBonos");
	}
	/**
	 * Gets the amount of bonos that an user has
	 * @param $nick
	 * @return unknown_type
	 */
	function getBonos($nick) {
		$query = $this->mdbSend("SELECT BONOS $nick");
		return $query;
	}
	/**
	 * Sets the amount of bonos that an user should have
	 * @param $nick
	 * @param $quantity
	 * @return unknown_type
	 */
	function setBonos($nick,$quantity) {
		$this->mdbSend("UPDATE BONOS $nick $quantity");
	}
 
	// misc functions
 
	/**
	 * Says how much time has elapsed since one timestamp in a verbose way
	 * @param $desde
	 * @return unknown_type
	 */
	function timeDiference($desde){ //hecho por Adri�n Navarro adri@adrinavarro.com
		$texto = '';
		$ahora = time();
		$diferencia = $ahora - $desde;
		$dias = intval($diferencia/86400);
		$diferencia = $diferencia%86400;
		$horas = intval($diferencia/3600);
		$diferencia = $diferencia%3600;
		$minutos = intval($diferencia/60);
		if ($dias > 1) $texto .= " $dias ". 'dias';
		else if ($dias == 1) $texto .= " $dias ". 'dia';
		if ($horas > 1) $texto .= " $horas ". 'horas';
		else if ($horas == 1) $texto .= " $horas ". 'hora';
		if ($minutos > 1) $texto .= " $minutos ". 'minutos';
		else if ($minutos == 1) $texto .= " $minutos " . 'minuto';
		if ($texto == '') $texto .= ' '. 'pocos segundos';
		return $texto;
	}
	/**
	 * Sets were an user should be in the Oca's game
	 * @param $nick
	 * @param $casilla
	 * @return unknown_type
	 */
	function setCasillaOca($nick,$casilla) {
		$this->dbSend("UPDATE ".DB_PREFIX."oca SET `casilla`='$casilla' WHERE `nick`='$nick' AND `is_finished`='0'");
	}

	//log functions
	
	/**
	 * Opens the log descriptor
	 * @return unknown_type
	 */
	function openLog() {
		$logName = $this->getLogName();
		$this->logfd = fopen(LOG_DIR.$logName,"a+t");
		return $this->logfd;
	}
	/**
	 * Checks if the log is readable/writable or not.
	 * @return unknown_type
	 */
	function checkLog() {
		$logName = $this->getLogName();
		$exists = file_exists(LOG_DIR.$logName);
		if ($exists) {
			if (!is_readable(LOG_DIR.$logName) || (!is_writable(LOG_DIR.$logName))) return false;
			else return true;
		}
		else return $exists;
	}
	/**
	 * Gets the name of the log file. It parses all the wildcards from the config file
	 * @return unknown_type
	 */
	function getLogName() {
		$wildcards = array('%d','%m','%y','%h','%min','%s','%u');
		$parseWildcards = array('d','m','y','H','i','s','U');
		$wildcardParse = str_replace($wildcards,$parseWildcards,LOG_WILDCARD);
		$fileName = date($wildcardParse).".log";
		return $fileName;
	}
	/**
	 * Writes something to the log file with the date
	 * @param $data
	 * @return unknown_type
	 */
	function writeLog($data) {
		$check = $this->checkLog();
		if ($check) {
			$data = "[".date("H:i:s")."] $data\n";
			fwrite($this->logfd,$data);
		}
	}
	/**
	 * It writes something directly to a log file
	 * @param $data
	 * @return unknown_type
	 */
	function writeRawLog($data) {
		$check = $this->checkLog();
		if ($check) fwrite($this->logfd,$data."\n");
	}
	/**
	 * Writes something to the log file of a channel
	 * @param $channel
	 * @param $category
	 * @param $data
	 * @return unknown_type
	 */
	function writeChannelLog($channel,$category,$data=NULL) {
		$channel = str_replace("#","",$channel);
		$logfd = fopen(LOG_DIR."channels/".urlencode($channel).".log","at");
		$dataToWrite = serialize(array(time(),$category,$data))."\n";
		fwrite($logfd,$dataToWrite);
		fclose($logfd);
	}
	/**
	 * Returns the content of the log file of a channel
	 * @param $channel
	 * @param $lines
	 * @return unknown_type
	 */
	function readChannelLog($channel,$lines) {
		$channel = str_replace("#","",$channel);
		if (!is_readable(LOG_DIR."channels/".urlencode($channel).".log")) return false;
		else {
			$fileContents = file(LOG_DIR."channels/".urlencode($channel).".log");
			foreach ($fileContents AS $line) $fileContent[] = str_replace("\n","",str_replace("\r","",$line));
			if ($lines > count($fileContent)) $toRead = count($fileContent);
			else $toRead = count($fileContent) - (count($fileContent) - $lines);
			$toReturn = array();
			for ($i = (count($fileContent) - 1); count($toReturn) < $toRead; $i--) {
				if (strlen($fileContent[$i]) != 0 && (isset($fileContents[$i]))) { $toReturn[] = $fileContents[$i]; }
			}
			return $toReturn;
		}
	}
	/**
	 * Writes something into the log of an user
	 * @param $nick
	 * @param $category
	 * @param $data
	 * @return unknown_type
	 */
	function writeUserLog($nick,$category,$data=NULL) {
		$nick = urlencode($nick);
		$logfd = fopen(LOG_DIR."users/$nick.log","at");
		$dataToWrite = serialize(array(time(),$category,$data))."\n";
		fwrite($logfd,$dataToWrite);
		fclose($logfd);
	}
	/**
	 * Returns the content of the log of an user
	 * @param $nick
	 * @param $lines
	 * @return unknown_type
	 */
	function readUserLog($nick,$lines) {
		$nick = urlencode($nick);
		if (!is_readable(LOG_DIR."users/$nick.log")) return false;
		else {
			$fileContents = file(LOG_DIR."users/$nick.log");
			foreach ($fileContents AS $line) $fileContent[] = str_replace("\n","",str_replace("\r","",$line));
			if ($lines > count($fileContent)) $toRead = count($fileContent);
			else $toRead = count($fileContent) - (count($fileContent) - $lines);
			$toReturn = array();
			for ($i = (count($fileContent) - 1);count($toReturn) <= $toRead;$i--) {
				if (strlen($fileContent[$i]) != 0 && (isset($fileContent[$i]))) { $toReturn[] = $fileContent[$i]; }
			}
			return $toReturn;
		}
	}
	/**
	 * Writes into the log of an operator
	 * @param $nick
	 * @param $category
	 * @param $data
	 * @return unknown_type
	 */
	function writeOperLog($nick,$category,$data=NULL) {
		$nick = urlencode($nick);
		$logfd = fopen(LOG_DIR."opers/$nick.log","at");
		$dataToWrite = serialize(array(time(),$category,$data))."\n";
		fwrite($logfd,$dataToWrite);
		fclose($logfd);
	}
	/**
	 * Returns the content of the log file of an operator
	 * @param $nick
	 * @param $lines
	 * @return unknown_type
	 */
	function readOperLog($nick,$lines) {
		$nick = urlencode($nick);
		if (!is_readable(LOG_DIR."opers/$nick.log")) return false;
		else {
			$fileContents = file(LOG_DIR."opers/$nick.log");
			foreach ($fileContents AS $line) $fileContent[] = str_replace("\n","",str_replace("\r","",$line));
			if ($lines > count($fileContent)) $toRead = count($fileContent);
			else $toRead = count($fileContent) - (count($fileContent) - $lines);
			$toReturn = array();
			for ($i = (count($fileContent) - 1);count($toReturn) <= $toRead;$i--) {
				if (strlen($fileContent[$i]) != 0 && (isset($fileContent[$i]))) { $toReturn[] = $fileContent[$i]; }
			}
			return $toReturn;
		}
	}
	
	//bank functions
	
	/**
	 * Gets the bank that an user has
	 * @param $nick
	 * @return unknown_type
	 */
	function getBank($nick) {
		$query = $this->dbSend("SELECT banco FROM ".DB_PREFIX."bancos WHERE `nick`='$nick'");
		if (!mysql_num_rows($query)) return false;
		else {
			$result = mysql_result($query,0);
			return $result;
		}
	}
	/**
	 * Sets a bank to an user
	 * @param $nick
	 * @param $bank
	 * @return unknown_type
	 */
	function setBank($nick,$bank) {
		$query = $this->dbSend("UPDATE ".DB_PREFIX."bancos SET `banco`='$bank' WHERE `nick`='$nick'");
		if (!mysql_affected_rows()) $this->dbSend("INSERT INTO ".DB_PREFIX."bancos SET `banco`='$bank', `nick`='$nick', `dinero`='0'");
	}
	/**
	 * Gets the amount of money that an user has in a bank account
	 * @param $nick
	 * @return unknown_type
	 */
	function getBankMoney($nick) {
		$query = $this->dbSend("SELECT dinero FROM ".DB_PREFIX."bancos WHERE `nick`='$nick'");
		if (mysql_num_rows($query)) {
			$money = mysql_result($query,0);
			return $money;
		}
		else return false;
	}
	/**
	 * Adds money to a bank account.
	 * @param $nick
	 * @param $quantity
	 * @param $reason
	 * @param $person
	 * @return unknown_type
	 */
	function addBankMoney($nick,$quantity,$reason=NULL,$person=NULL) {
		$money = $this->getBankMoney($nick);
		$postMoney = bcadd($money,$quantity);
		$this->dbSend("UPDATE ".DB_PREFIX."bancos SET `dinero`='$postMoney' WHERE `nick`='$nick'");
		if (!is_null($reason)) {
			if (!is_null($person)) $reason = str_replace("%person",$person,$reason);
			$this->dbSend("INSERT INTO ".DB_PREFIX."bancosmov SET `ctime`='".time()."', `nick`='$nick', `desc`='$reason', `type`='h', `cant`='$quantity'");
		}
	}
	/**
	 * It deletes money from a bank account
	 * @param $nick
	 * @param $quantity
	 * @param $reason
	 * @param $person
	 * @return unknown_type
	 */
	function delBankMoney($nick,$quantity,$reason=NULL,$person=NULL) {
		$money = $this->getBankMoney($nick);
		$postMoney = bcsub($money,$quantity);
		$this->dbSend("UPDATE ".DB_PREFIX."bancos SET `dinero`='$postMoney' WHERE `nick`='$nick'");
		if (!is_null($reason)) {
			if (!is_null($person)) $reason = str_replace("%person",$person,$reason);
			$this->dbSend("INSERT INTO ".DB_PREFIX."bancosmov SET `ctime`='".time()."', `nick`='$nick', `desc`='$reason', `type`='d', `cant`='$quantity'");
		}
	}
	/**
	 * It calculates how much profit did the user gain
	 * @param $nick
	 * @param $money
	 * @return unknown_type
	 */
	function bankIntereses($nick,$money) {
		$bank = $this->getBank($nick);
		if ($bank) {
			switch ($bank) {
				case 'topbanco': $toAdd = 0;
				case 'interbanco': $toAdd = 2;
				case 'banconacional': $toAdd = 5;
			}
			if ($toAdd > 0) {
				$percent = $toAdd / 100;
				$intereses = bcmul($money,$percent,0);
				if ($intereses) $this->addBankMoney($nick,$intereses,'Intereses');
			}
		}
	}
	
	//prettier message functions
	
	/**
	 * It gives color format to a message
	 * @param $color
	 * @param $message
	 * @return unknown_type
	 */
	function c($color,$message) {
		$message = "$color".$message.'';
		return $message;
	}
	/**
	 * It gives bold format to a message
	 * @param $message
	 * @return unknown_type
	 */
	function b($message) {
		$message = ''.$message.'';
		return $message;
	}
	/**
	 * It highlights a message
	 * @param $message
	 * @return unknown_type
	 */
	function h($message) {
		$result = $this->c(12,$message);
		return $result;
	}
	/**
	 * It underlines a message
	 * @param $message
	 * @return unknown_type
	 */
	function u($message) {
		$message = ''.$message.'';
		return $message;
	}
	
	//default responses
	
	/**
	 * It sends the default response for a non-registered user
	 * @param $canal
	 * @param $nick
	 * @return unknown_type
	 */
	function msgNoRegistered($canal,$nick) {
		$this->ircMsg($canal, $this->h($nick).", necesitas estar registrado para poder hacer uso de los comandos del bot. Escribe ".$this->h('!alta')." para darte de alta");
	}
	/**
	 * It sends the default response when a command isn't used as it should be
	 * @param $canal
	 * @param $text
	 * @return unknown_type
	 */
	function msgSintaxError($canal,$text) {
		$this->ircMsg($canal,'Sintaxis incorrecta: '.$this->h($text), true);
	}

	//ping functions

	/**
	 * It sends a ping to the ping Server
	 * @param $status
	 * @return unknown_type
	 */
	function doPing($status='on') {
		$url = PING_HOST.':'.PING_PORT.'/'.PING_PATH.'?num='.BOT_NUMBER.'&token='.BOT_TOKEN.'&status='.$status.'&cctime='.$this->ctime;
		$curl = curl_init($url);
		curl_setopt($curl,CURLOPT_USERAGENT,"topgames ".TOPGAMES_VERSION);
		curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
		$result = curl_exec($curl);
		curl_close($curl);
		if ($result) {
			$split = explode(' ', $result);
			if ($split[0] == 'OK') return true;
			else {
				global $_CFG;
				if ($this->ircconnected == true) $this->ircMsg(CHANNEL, 'Error al intentar mandar un ping al servidor de sincronizacion. Error '.$split[1]);
				if (LOG_STATUS && (in_array('errors',$_CFG['LOG_REC']))) $this->writeLog('error al intentar mandar un ping al servidor de sincronizacion. error '.$split[1]);
				return false;
			}
		}
	}
}

?>